package com.zzyl.listener;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.zzyl.dto.ContentDTO;
import com.zzyl.entity.DeviceData;
import com.zzyl.service.AlertRuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Component
public class RedisQueueListener implements MessageListener {

    @Resource
    AlertRuleService alertRuleService;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String s = new String(message.getBody());
        String topic = new String(message.getChannel());
        System.out.println("监听到消息" + s + "来自" + topic);
        ContentDTO contentDTO = JSONObject.parseObject(s, ContentDTO.class);
        log.info("一曲肝肠断，天涯何处觅知音{}", contentDTO);
        Map<String, ContentDTO.Item> items = contentDTO.getItems();
        if (Objects.isNull(items)){
            return;
        }
        List<DeviceData> collect = items.entrySet().stream().map(item -> {
            DeviceData deviceData = new DeviceData();
            deviceData.setDeviceName(contentDTO.getDeviceName());
            deviceData.setIotId(contentDTO.getIotId());
            deviceData.setNoteName("");
            deviceData.setProductId(contentDTO.getProductKey());
            deviceData.setProductName("");
            deviceData.setFunctionName(item.getKey());
            deviceData.setAccessLocation("");
            deviceData.setDataValue(item.getValue().getValue() + "");
            LocalDateTime localDateTime = LocalDateTimeUtil.of(item.getValue().getTime());
            deviceData.setAlarmTime(localDateTime);
            return deviceData;
        }).collect(Collectors.toList());
        alertRuleService.alertFilter(collect);
    }
}
